/*
 * Copyright 2019 Alex Andres
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dev.onvoid.webrtc.demo.javafx.view;

import static java.util.Objects.nonNull;

import dev.onvoid.webrtc.demo.javafx.util.FxUtils;
import dev.onvoid.webrtc.demo.view.ConsumerAction;
import dev.onvoid.webrtc.demo.view.DesktopSourceView;
import dev.onvoid.webrtc.demo.view.DesktopSourcesView;
import dev.onvoid.webrtc.media.video.desktop.DesktopSourceType;

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;

@FxmlView(name = "desktop-sources")
public class FxDesktopSourcesView extends GridPane implements DesktopSourcesView {

	@FXML
	private Pane screenPane;

	@FXML
	private Pane windowPane;

	private ConsumerAction<DesktopSourceView> sourceViewAction;


	@Override
	public void addDesktopSourceView(DesktopSourceView view) {
		FxUtils.checkNodeView(view);

		FxUtils.invoke(() -> {
			boolean added = false;

			if (view.getDesktopSourceType() == DesktopSourceType.SCREEN) {
				added = screenPane.getChildren().add((Node) view);
			}
			else if (view.getDesktopSourceType() == DesktopSourceType.WINDOW) {
				added = windowPane.getChildren().add((Node) view);
			}

			if (added) {
				view.setOnClick(() -> {
					if (nonNull(sourceViewAction)) {
						sourceViewAction.execute(view);
					}
				});
			}
		});
	}

	@Override
	public void removeDesktopSourceView(DesktopSourceView view) {
		FxUtils.checkNodeView(view);

		FxUtils.invoke(() -> {
			if (view.getDesktopSourceType() == DesktopSourceType.SCREEN) {
				screenPane.getChildren().remove((Node) view);
			}
			else if (view.getDesktopSourceType() == DesktopSourceType.WINDOW) {
				windowPane.getChildren().remove((Node) view);
			}
		});
	}

	@Override
	public void setOnDesktopSourceView(ConsumerAction<DesktopSourceView> consumer) {
		this.sourceViewAction = consumer;
	}

	@FXML
	private void initialize() {
		for (var node : lookupAll(".scroll-pane")) {
			ScrollPane pane = (ScrollPane) node;
			pane.skinProperty().addListener(new InvalidationListener() {

				@Override
				public void invalidated(Observable observable) {
					pane.skinProperty().removeListener(this);

					var viewport = pane.lookup(".viewport");
					viewport.setCache(false);
				}
			});
		}
	}
}
